package com.asset.dispoal.commom.version;

import com.asset.dispoal.commom.version.annoation.SqlVersion;
import com.asset.dispoal.commom.version.strategy.VersionStrategyManager;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.strategy.StrategyHandlerParam;
import tech.mhuang.pacebox.core.strategy.StrategyHandlerResult;

import java.lang.reflect.Method;

/**
 * @author qr
 * @date 2022/2/16$
 */
@Aspect
@Component
public class SqlVersionAspect {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private VersionStrategyManager versionStrategyManager;


    @After("@annotation(com.asset.dispoal.commom.version.annoation.SqlVersion)")
    public void after(JoinPoint joinPoint) throws Exception {
        MethodSignature method = (MethodSignature) joinPoint.getSignature();
        SqlVersion sqlVersion = getAnnoationByMethod(method);
        final String value = sqlVersion.value();
        String sql = SqlUtils.getMybatisSql(joinPoint, sqlSessionFactory);
        StrategyHandlerResult<String> strategy = versionStrategyManager.strategy(new StrategyHandlerParam<>(value.toUpperCase(), sql));
        String data = strategy.getData();
        SqlExecute.execute(data);
    }


    private SqlVersion getAnnoationByMethod(MethodSignature methodSignature) {
        Method method0 = methodSignature.getMethod();
        return method0.getAnnotation(SqlVersion.class);
    }
}
